package com.szsky.sky.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class HolidayUtils {
    // 缓存节假日数据，避免频繁请求
    private static final Map<Integer, Set<LocalDate>> HOLIDAY_CACHE = new HashMap<>();
    // 缓存调休数据，避免频繁请求
    private static final Map<Integer, Set<LocalDate>> WORKDAY_CACHE = new HashMap<>();
    // 节假日API地址
    private static final String HOLIDAY_API = "https://timor.tech/api/holiday/year/";

    /**
     * 判断指定日期是否为节假日或周末
     * @param date 待判断的日期字符串，格式：yyyy-MM-dd
     * @return 如果是节假日或周末返回true，否则返回false
     */
    public static boolean isHolidayOrWeekend(String date) {
        LocalDate localDate = LocalDate.parse(date, DateTimeFormatter.ISO_LOCAL_DATE);
        return isHolidayOrWeekend(localDate);
    }

    /**
     * 判断指定日期是否为节假日或周末
     * @param date 待判断的日期
     * @return 如果是节假日或周末返回true，否则返回false
     */
    public static boolean isHolidayOrWeekend(LocalDate date) {
        // 先判断是否为周末
        DayOfWeek dayOfWeek = date.getDayOfWeek();
        if (dayOfWeek == DayOfWeek.SATURDAY || dayOfWeek == DayOfWeek.SUNDAY) {
            return true;
        }

        // 判断是否为法定节假日
        try {
            loadHolidayDataIfNeeded(date.getYear());
            return HOLIDAY_CACHE.get(date.getYear()).contains(date);
        } catch (Exception e) {
            System.err.println("获取节假日数据失败，使用默认判断逻辑: " + e.getMessage());
            return false;
        }
    }

    /**
     * 判断指定日期是否为调休工作日
     * @param date 待判断的日期
     * @return 如果是调休工作日返回true，否则返回false
     */
    public static boolean isWorkingDay(LocalDate date) {
        try {
            loadHolidayDataIfNeeded(date.getYear());
            return WORKDAY_CACHE.get(date.getYear()).contains(date);
        } catch (Exception e) {
            System.err.println("获取调休数据失败，使用默认判断逻辑: " + e.getMessage());
            return false;
        }
    }

    /**
     * 如果需要，加载指定年份的节假日数据
     * @param year 年份
     */
    private static void loadHolidayDataIfNeeded(int year) {
        if (HOLIDAY_CACHE.containsKey(year) && WORKDAY_CACHE.containsKey(year)) {
            return;
        }

        synchronized (HolidayUtils.class) {
            if (!HOLIDAY_CACHE.containsKey(year) || !WORKDAY_CACHE.containsKey(year)) {
                fetchAndCacheHolidayData(year);
            }
        }
    }

    /**
     * 从API获取并缓存指定年份的节假日数据
     * @param year 年份
     */
    private static void fetchAndCacheHolidayData(int year) {
        try {
            String apiUrl = HOLIDAY_API + year;
            String response = HttpUtil.get(apiUrl);
            JSONObject json = JSONUtil.parseObj(response);

            if (!"0".equals(json.getStr("code"))) {
                throw new RuntimeException("获取节假日数据失败，错误码: " + json.getStr("code"));
            }

            JSONObject holidayInfo = json.getJSONObject("holiday");
            Set<LocalDate> holidays = new HashSet<>();
            Set<LocalDate> workdays = new HashSet<>();

            for (Object key : holidayInfo.keySet()) {
                JSONObject dayInfo = holidayInfo.getJSONObject(key.toString());
                LocalDate date = LocalDate.parse(dayInfo.getStr("date"), DateTimeFormatter.ISO_LOCAL_DATE);
                
                // 类型：0-工作日、1-周末、2-节假日、3-调休工作日
                int type = dayInfo.getInt("type", 0);
                if (type == 2) {
                    holidays.add(date);
                } else if (type == 3) {
                    workdays.add(date);
                }
            }

            HOLIDAY_CACHE.put(year, holidays);
            WORKDAY_CACHE.put(year, workdays);
        } catch (Exception e) {
            System.err.println("获取" + year + "年节假日数据异常: " + e.getMessage());
            // 设置空集合避免重复请求
            HOLIDAY_CACHE.put(year, Collections.emptySet());
            WORKDAY_CACHE.put(year, Collections.emptySet());
            throw e;
        }
    }

//    public static void doPost1() {
//        String body = HttpRequest.post("http://10.60.0.14:8080/DreamWeb/ctrl/flow/clearFlow")
//                .header("accept", "application/json, text/javascript, */*; q=0.01")//头信息，多个头信息多次调用此方法即可
//                .header("Cookie", "SESSION=7c25f75f-86c6-45a0-9dff-8e9b647fc699; JSESSIONID=4F6455CEE7C4D64D0F0B2287BF7811CB")
//                .execute().body();
//        // 直接转换为Map
//        Map<String, Object> map = JSON.parseObject(body, Map.class);
//
//        // 输出转换后的Map
//        for (String key : map.keySet()) {
//            System.out.println(key + ": " + map.get(key));
//        }
//    }
//
//    public static void doPost2() {
//        String body = HttpRequest.post("http://10.60.0.14:8080/DreamWeb/ctrl/rediscache/clear")
//                .header("accept", "application/json, text/javascript, */*; q=0.01")//头信息，多个头信息多次调用此方法即可
//                .header("Cookie", "SESSION=7c25f75f-86c6-45a0-9dff-8e9b647fc699; JSESSIONID=4F6455CEE7C4D64D0F0B2287BF7811CB")
//                .execute().body();
//        // 直接转换为Map
//        Map<String, Object> map = JSON.parseObject(body, Map.class);
//
//        // 输出转换后的Map
//        for (String key : map.keySet()) {
//            System.out.println(key + ": " + map.get(key));
//        }
//    }
//
//    public static void doPost3() {
//        String body = HttpRequest.post("http://10.60.0.14:8080/DreamWeb/ctrl/usersync/sendUserSync")
//                .header("accept", "application/json, text/javascript, */*; q=0.01")//头信息，多个头信息多次调用此方法即可
//                .header("Cookie", "SESSION=OTMyOTdiNGUtMDg5Yi00NWQwLWE2Y2QtYTJkOWU5MTE5ZjQ2; JSESSIONID=4F6455CEE7C4D64D0F0B2287BF7811CB")
//                .execute().body();
//        // 直接转换为Map
//        Map<String, Object> map = JSON.parseObject(body, Map.class);
//
//        // 输出转换后的Map
//        for (String key : map.keySet()) {
//            System.out.println(key + ": " + map.get(key));
//        }
//    }
//
//    public static void doPost4() {
//        String body = HttpRequest.post("http://10.60.0.14:8080/DreamWeb/ctrl/single/login")
//                .execute().body();
//        System.out.println(body);
//    }

    public static void main(String[] args) {
        // 测试示例
        System.out.println("2025-06-26 是否为节假日或周末: " + isHolidayOrWeekend("2025-06-28")); // 元旦，是
    }
}    